#ifndef V7_C
#define V7_C

#include <cv.h>

namespace v7 {

std::vector<cv::Point> findContour(cv::Mat_<int> pointMat) {
	std::vector<cv::Point> dir(4); //+1 is right, -1 is left
	dir[0] = cv::Point(0,1); //down
	dir[1] = cv::Point(-1,0); //left
	dir[2] = cv::Point(0,-1); //up
	dir[3] = cv::Point(1,0); //right
	
	std::vector<cv::Point> contour;
	
	cv::Point p;
	bool found = false;
	
	//find starting point
	for (uint y = 0; y < pointMat.rows && !found; y++) {
		for (uint x = 0; x < pointMat.cols && !found; x++) {
			if (pointMat(y, x) == 255) {
				p = cv::Point(x, y);
				found = true;
			}
		}
	}
	
	assert(found); //or else it was empty
	
	//do that one rule from the pdf
	bool end = false;
	uint d = 0;
	int subsequent = 0; //prevent multiple additions of same points
	cv::Point start = p;
	contour.push_back(p);
	
	while (!end) {
		p += dir[d % dir.size()];
		int v = 0;
		if (p.x >= 0 && p.y >= 0 && p.x < pointMat.cols && p.y < pointMat.rows) {
			v = pointMat(p.y, p.x);
		}
		if (v == 255) {
			d++;
			if (p.x == start.x && p.y == start.y) {
				end = true;
			} else if (subsequent < 3){
				contour.push_back(p);
			}
			subsequent = 0;
		} else {
			d--;
			subsequent++;
		}
	}
	return contour;
}
}

#endif
